import os
import datetime
import ujson as json

import coin.strategy.mm.fastfeature.linear_model_factory as lmf
from coin.strategy.mm.fastfeature.feed_manager import get_tick_size, get_target_tick_size
from coin.strategy.hk_hard_arb.util import parse_feed_subreqs_config
from coin.strategy.accounting.pnl_balance_printer.util import get_quote_currency
from coin.strategy.mm.feed import SubscriptionRequest


class ModelFastProfile(object):
  def __init__(self,
               *,
               profile_name,
               trade_subreq,
               feed_subreqs=None,
               linear_alpha_file=None,
               datetime_override=None,
               profile_root=None,
               **exec_kwargs):
    if profile_root is None:
      profile_root = 'profile'
    if linear_alpha_file is None:
      linear_alpha_file = "linear_alpha.json"
    self.profile_path = f"{profile_root}/{profile_name}/{linear_alpha_file}"
    print(self.profile_path)
    edge_info_path = f"{profile_root}/{profile_name}/edge_info.json"

    if os.path.exists(edge_info_path):
      self.edge_info = json.load(open(edge_info_path, 'r'))
    else:
      self.edge_info = None

    if datetime_override is not None:
      self.model, self.product_map, self.aggregation_map, self.targets =\
          lmf.create_linear_model2(self.profile_path, datetime_override)
      self.converter_factory = lmf.LmConverterFactory(self.profile_path,
                                                      self.product_map,
                                                      datetime_override)
    else:
      self.model, self.product_map, self.aggregation_map, self.targets =\
          lmf.create_linear_model2(self.profile_path, datetime.datetime.now())
      self.converter_factory = lmf.LmConverterFactory(self.profile_path,
                                                      self.product_map,
                                                      datetime.datetime.now())

    self.product = self.targets[0]
    self.currency = list({self.product.base, get_quote_currency(self.product)})
    self.tick = get_tick_size(self.product)
    self.sub_key = SubscriptionRequest.from_dict(trade_subreq)
    self.feed_subreqs = parse_feed_subreqs_config(feed_subreqs)
    self.feed_subreq = self.converter_factory.feedspec.feed_sub_request
    self.exec_kwargs = exec_kwargs
    self.execution_params = {
        'product': self.product,
        'currency': self.currency,
        'stickiness': get_target_tick_size(self.product) * 0.5,
        'tick_size': get_target_tick_size(self.product),
        'edge_info': self.edge_info
    }
    self.execution_params.update(self.exec_kwargs)
